package org.wishwork.api.base.wms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wishwork.api.Api;
import org.wishwork.api.token.get.ResponseToken;
import org.wishwork.cache.DefaultMemoryCacheOperator;
import org.wishwork.constant.Constants;
import org.wishwork.context.Context;
import org.wishwork.helper.HttpHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 仓库查询
 * @author: WangYX
 * @create: 2022-04-02 16:52
 * @Version: 1.0.0
 **/

public class WmsApi extends Api<List<WmsResponse>, WmsRequest> {

    private static final Logger log = LoggerFactory.getLogger(WmsApi.class);

    private Context context;

    public WmsApi(Context context) {
        this.context = context;
    }

    /**
     * 调用聚水潭 仓库查询
     *
     * @param wmsRequest
     * @return
     * @throws Exception
     */
    @Override
    protected String query(WmsRequest wmsRequest) throws Exception {

        ResponseToken token = (ResponseToken) DefaultMemoryCacheOperator.instance().get(Constants.TOKEN);

        String url = "/open/wms/partner/query";
        //请求参数
        Map<String, Object> params = new HashMap<>(2);
        params.put("page_index", wmsRequest.getPageIndex());
        params.put("page_size", wmsRequest.getPageSize());
        String biz = JSON.toJSONString(params);
        String result = HttpHelper.sendRequest(token.getAccessToken(), biz, url);
        return result;
    }

    /**
     * 仓库业务处理
     *
     * @param data       请求返回的json数据
     * @param wmsRequest 请求的对象
     * @return
     * @throws Exception
     */
    @Override
    protected List<WmsResponse> process(JSONObject data, WmsRequest wmsRequest) throws Exception {
        JSONArray datas = data.getJSONArray("datas");
        List<WmsResponse> wmsResponses = datas.toJavaList(WmsResponse.class);
        //判断是否还有下一个
        Boolean has_next = data.getBoolean("has_next");
        if (has_next) {
            Integer index = wmsRequest.getPageIndex();
            WmsRequest build = wmsRequest.toBuilder().pageIndex(++index).build();
            List<WmsResponse> result = business(build);
            wmsResponses.addAll(result);
        }
        return wmsResponses;
    }
}
